package org.jeecg.modules.bus.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.annotation.ApiLogin;
import org.jeecg.com.util.ThirdSessionHolder;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.TenantContextHolder;
import org.jeecg.config.ApiVersion;
import org.jeecg.config.ApiVersionConstant;
import org.jeecg.config.WebConfig;
import org.jeecg.modules.bus.vo.BusServiceRepairCategoryVo;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.*;
import org.jeecg.modules.order.entity.CesOrderRepair;
import org.jeecg.modules.order.service.ICesOrderRepairService;
import org.jeecg.modules.rooms.entity.CesRooms;
import org.jeecg.modules.rooms.service.CesRoomsServiceImpl;
import org.jeecg.modules.mall.entity.MallUserInfo;
import org.jeecg.modules.wxuser.service.IUserInfoService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
* @Description: ces_order_repair
* @Author: jeecg-boot
* @Date:   2023-03-27
* @Version: V1.0
*/
@Api(tags="服务维修单")
@RestController
@RequestMapping("/mall-api/hotel-order-repair")
@Slf4j
public class OrderRepairController extends WebConfig {
   @Resource
   private ICesOrderRepairService cesOrderRepairService;
    @Resource
    private IBusHotelService busHotelService;
    @Resource
    private IUserInfoService userInfoService;
    @Resource
    private IBusRoomsLivingOrderService busRoomsLivingOrderService;
    @Resource
    private IBusRoomBookingOrdersService busRoomBookingOrdersService;
    @Resource
    private IBusBookingRoomsService busBookingRoomsService;
    @Resource
    private CesRoomsServiceImpl cesRoomsService;
    @Resource
    private IBusServiceRepairService busServiceRepairService;
    @Resource
    private IBusServiceRepairCategoryService busServiceRepairCategoryService;
   /**
    * 服务维修单分页列表查询
    *
    * @param cesOrderRepair
    * @param pageNo
    * @param pageSize
    * @param req
    * @return
    */
   @ApiLogin
   @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
   @ApiOperation(value="服务维修单分页列表查询", notes="服务维修单分页列表查询")
   @GetMapping(value = "/list")
   public Result<IPage<CesOrderRepair>> queryPageList(CesOrderRepair cesOrderRepair,
                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                      @RequestParam(name="startTime",required = false) String startTime,
                                                      @RequestParam(name="endTime",required = false) String endTime,
                                  HttpServletRequest req) {
       LambdaQueryWrapper<CesOrderRepair> queryWrapper = QueryGenerator.initQueryWrapper(cesOrderRepair, req.getParameterMap()).lambda();
       String tenantId = TenantContextHolder.getTenantId();
       String userId = ThirdSessionHolder.getUserId();
       queryWrapper.eq(CesOrderRepair::getUserId,userId);
       Page<CesOrderRepair> page = new Page<CesOrderRepair>(pageNo, pageSize);
       IPage<CesOrderRepair> pageList = cesOrderRepairService.page(page, queryWrapper);
       pageList.getRecords().forEach(item -> {
           BusHotel hotel = busHotelService.getById(item.getHotelId());
           if (hotel != null) {
               item.setHotelName(hotel.getName());
           }
       });
       return Result.OK(pageList);
   }

   /**
    *   服务/维修单添加
    *
    * @param cesOrderRepair
    * @return
    */
   @AutoLog(value = "服务/维修单添加")
   @ApiOperation(value="服务/维修单添加", notes="服务/维修单添加")
   @ApiLogin
   @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
   @PostMapping(value = "/add")
   public Result<String> add(@RequestBody CesOrderRepair cesOrderRepair) {
       String tenantId = TenantContextHolder.getTenantId();
       String userId = ThirdSessionHolder.getUserId();
       cesOrderRepair.setTenantId(tenantId);
       cesOrderRepair.setUserId(userId);
       cesOrderRepair.setCreateDate(DateTime.now());
       String prefix = "FW";
       if (cesOrderRepair.getType().equals(2)) {
           prefix = "WX";
       }
       cesOrderRepair.setOrderId(randomNumber(prefix));
       MallUserInfo mallUserInfo = userInfoService.getById(userId);
       if (mallUserInfo != null) {
           cesOrderRepair.setUserMobile(mallUserInfo.getMobile());
           cesOrderRepair.setUserName(mallUserInfo.getNickName());
       }
       LambdaQueryWrapper<BusRoomsLivingOrder> lambdaQueryWrapper = new LambdaQueryWrapper<>();
       lambdaQueryWrapper.eq(BusRoomsLivingOrder::getThirdLoginUserId, userId).orderByDesc(BusRoomsLivingOrder::getCreateTime).last("limit 1");
       BusRoomsLivingOrder busRoomsLivingOrder = busRoomsLivingOrderService.getOne(lambdaQueryWrapper);
       if (busRoomsLivingOrder != null && StringUtils.isNotBlank(busRoomsLivingOrder.getBookingOrderId())) {
           LambdaQueryWrapper<BusBookingRooms> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
           lambdaQueryWrapper1.eq(BusBookingRooms::getBookingOrdersId, busRoomsLivingOrder.getBookingOrderId()).last("limit 1");
           BusBookingRooms bookingRooms = busBookingRoomsService.getOne(lambdaQueryWrapper1);
           if (bookingRooms != null) {
               CesRooms cesRooms = cesRoomsService.getById(bookingRooms.getRoomId());
               if (cesRooms != null) {
                   cesOrderRepair.setRoomNo(cesRooms.getName());
               }
           }
       }
       cesOrderRepair.setStatus(1);
       cesOrderRepairService.save(cesOrderRepair);
       return Result.OK("添加成功！");
   }

    /**
     * 生成16位数字+prefix
     * @param prefix
     * @return
     */
    private String randomNumber(String prefix) {
        int first = new Random(10).nextInt(8) + 1;
        int hashCode = UUID.randomUUID().toString().hashCode();
        if (hashCode < 0) {
            hashCode = -hashCode;
        }
        return prefix + first + String.format("%015d", hashCode);
    }

    /**
     * 维修项目列表
     * @param hotleId
     * @return
     */
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiOperation(value="维修项目列表", notes="维修项目列表")
    @GetMapping(value = "/repair-project-list")
    public Result<List<BusServiceRepair>> getRepairProjectList( @RequestParam(name="hotleId") String hotleId) {
        LambdaQueryWrapper<BusServiceRepair> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusServiceRepair::getHotelId, hotleId);
        queryWrapper.eq(BusServiceRepair::getType, 2);
        List<BusServiceRepair> list = busServiceRepairService.list(queryWrapper);
        return Result.OK(list);
    }

    /**
     * 服务项目列表
     * @param hotleId
     * @return
     */
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @ApiOperation(value="服务项目列表", notes="服务项目列表")
    @GetMapping(value = "/service-project-list")
    public Result<List<BusServiceRepairCategoryVo>> getServiceProjectList(@RequestParam(name="hotleId") String hotleId) {
        LambdaQueryWrapper<BusServiceRepairCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BusServiceRepairCategory::getHotelId, hotleId);
        List<BusServiceRepairCategoryVo> voList = new ArrayList<>();
        List<BusServiceRepairCategory> list = busServiceRepairCategoryService.list(queryWrapper);
        list.forEach(t -> {
            BusServiceRepairCategoryVo vo = new BusServiceRepairCategoryVo();
            vo.setName(t.getName());
            LambdaQueryWrapper<BusServiceRepair> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(BusServiceRepair::getHotelId, hotleId);
            lambdaQueryWrapper2.eq(BusServiceRepair::getType, 1);
            lambdaQueryWrapper2.eq(BusServiceRepair::getCategoryId, t.getId());
            List<BusServiceRepair> busServiceRepairs = busServiceRepairService.list(lambdaQueryWrapper2);
            vo.setList(busServiceRepairs);
            voList.add(vo);
        });
        return Result.OK(voList);
    }

    /**
     * 更改状态
     * @param dto
     * @return
     */
    @AutoLog(value = "服务维修订单更改状态")
    @ApiOperation(value="服务维修订单更改状态", notes="服务维修订单更改状态")
    @RequestMapping(value = "/setStauts", method = {RequestMethod.PUT,RequestMethod.POST})
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    public Result<String> setStauts(@RequestBody CesOrderRepair dto) {
        LambdaUpdateWrapper<CesOrderRepair> updateWrapper = new UpdateWrapper().lambda();
        updateWrapper.set(CesOrderRepair::getStatus, dto.getStatus());
        updateWrapper.eq(CesOrderRepair::getId, dto.getId());
        cesOrderRepairService.update(updateWrapper);
        return Result.OK("编辑成功!");
    }

    /**
     *   通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ces_order_repair-通过id删除")
    @ApiOperation(value="ces_order_repair-通过id删除", notes="ces_order_repair-通过id删除")
    @ApiLogin
    @ApiVersion(group = ApiVersionConstant.FAP_MALLAPI101)
    @PostMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name="id",required=true) String id) {
        cesOrderRepairService.removeById(id);
        return Result.OK("删除成功!");
    }
}
